<?php
/**
 * Created by PhpStorm.
 * Author: leishaofa
 * Date: 2017/1/18 11:51
 */
class AuthGroupModel extends Model
{
    protected $trueTableName = 'f_group';


    /**
     * 获取角色列表
     * @param int $type  0 平台系统管理员 1 企业系统操作人员 2 医药代表
     * @return array
     */
    public function getGroupList($type = 0)
    {
        switch ($type) {
            case 0:
                $description = 0;
                break;
            case 1:
                $description = 1;
                break;
            case 2:
                $description = 2;
                break;
        }
        $where = [
            'is_enable' => 1,
            /*'role_id' =>  ['neq', 1]*/   //TODO  正式时候需要隐藏超级管理员
            'description' => $description
        ];
        $count = $this->where($where)->count();
        $page = new \Think\Page($count, 1);
        $list = $this->where($where)->limit($page->firstRow, $page->listRows)->order('role_id DESC')->select();
        return array(
            'list' => $list,
            'page' => $page->show(),
        );
    }

    /**
     * 根据id查找角色信息
     * @param $id
     * @return mixed
     */
    public function findGroup($id)
    {
        $where = array(
            'group_id'   => $id,
            'is_enable' => 1,
        );
        return $this->where($where)->find();
    }

    /**
     * 根据id修改状态
     * @param $id
     * @param $status
     * @return bool
     */
    public function changeResult($id, $status)
    {
        $where = array(
            'role_id' => $id,
        );
        return $this->where($where)->setField('is_enable', $status);
    }

    /**
     * 角色分配权限
     * @param $rule_ids
     * @param $role_id
     * @return bool
     */
    public function addAuthRule($rule_ids, $role_id)
    {
        $where = array(
            'group_id' => $role_id,
        );

        $data = array(
            'group_val' => $rule_ids,
        );

        return $this->where($where)->save($data);
    }

    /**
     * 查询角色下有没有管理员存在
     * @param $id
     * @return mixed
     */
    public function isExistSonMember($id)
    {
        return $this->alias('a')
                ->join('left join f_action as b on a.role_id = b.role_id')
                ->where("a.role_id = $id and a.is_enable = 1")
                ->field('b.user_id')
                ->find();
    }
}